import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, DatePicker, Divider, Drawer, Form, Input, InputNumber, message, Modal, Select, Tag} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import OrderApplyForm from './components/OrderApplyForm';
import {
  addOrder,
  cstAfterSaleOrder,
  deductOrder,
  finishOrder, queryAfterSale,
  queryOrder,
  refundOrder,
  removeOrder,
  updateOrder
} from "@/services/order";
import moment from "moment";
import {receivableDetailByOrder} from "@/services/finance";


const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [scrapModalVisible, setScrapModalVisible] = useState(false);
  const [deductModalVisible, setDeductModalVisible] = useState(false);
  const [historyModalVisible, setHistoryModalVisible] = useState(false);
  const [title, setTitle] = useState('') // 1:客户扣款 2:客户报废补数 3：客户返修补数
  const actionRef = useRef();
  const historyRef = useRef();
  const [formRef] = Form.useForm();
  const [refundForm] = Form.useForm();
  const [deductForm] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRow, setSelectedRow] = useState({});
  const {Option} = Select;
  const {TextArea} = Input;
  const {RangePicker} = DatePicker;

  const handleScrapModalVisible = (record, type) => {
    setTitle(type === 1 ? '客户扣款' : type === 2 ? '客户报废补数' : '客户返修补数')
    refundForm.setFieldsValue({
      ...record,
      thisCstScrapNum: null,
      thisChargebackNum: null,
      thisToBeSuppliedNum: null,
      remark: null,
    })
    setSelectedRow(record)
    setScrapModalVisible(true)
  }
  const handleDeductModalVisible = (record) => {
    deductForm.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    setDeductModalVisible(true)
  }

  const handleHistoryModalVisible = (record) => {
    setSelectedRow(record)
    setRow(record)
    setHistoryModalVisible(true)
    if (historyRef.current) {
      historyRef.current.reload()
    }
  }


  const handleFinish = (record) => {
    try {
      finishOrder({
        ...record
      }).then(res => {
        if (res && res.status === '0') {
          message.success('订单已完结，即将刷新');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
        }
      });

      return true;
    } catch (error) {
      message.error('完结失败，请重试');
    }
  }

  const orderFinishConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `确认完成订单 【${record.orderCode} 】？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        handleFinish(record)
      }
    });
  }

  const handleScrapSubmit = (type) => {
    refundForm.validateFields(type === 2 ? [
      'thisCstScrapNum', 'thisToBeSuppliedNum','orderId','remark'
    ] : [
      'thisChargebackNum', 'thisToBeSuppliedNum','orderId','remark'
    ]).then(values => {
      cstAfterSaleOrder(type === 2 ? {
        orderId: values.orderId,
        cstScrapNum: values.thisCstScrapNum,
        toBeSuppliedNum: values.thisToBeSuppliedNum,
        remark: values.remark,
        serviceType: type
      } : {
        orderId: values.orderId,
        chargebackNum: values.thisChargebackNum,
        toBeSuppliedNum: values.thisToBeSuppliedNum,
        remark: values.remark,
        serviceType: type
      }).then(res => {
        if (res && res.status === '0') {
          message.success("提交成功")
          setScrapModalVisible(false)
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message)
        }
      })
    })
  }

  const handleDeductSubmit = () => {
    deductForm.validateFields().then(values => {
      cstAfterSaleOrder({
        orderCode: values.orderCode,
        deductByCust: values.deductByCustNew,
        orderId: selectedRow.orderId,
        serviceType: 1
      }).then(res => {
        if (res && res.status === '0') {
          message.success("更新扣款金额成功")
          setDeductModalVisible(false)
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message)
        }
      })
    })
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      width: 80,
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      tip: '订单编号是唯一的',
      hideInForm: true,
      copyable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入订单编号'}/>;
      }
    },
    {
      title: '产品编码',
      dataIndex: 'productCode',
    },
    {
      title: '生产编号',
      dataIndex: 'productionNo',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={11} placeholder={'请输入生产编号'}/>;
      }
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      width: 100,
      hideInForm: true,
      render: (text) => {
        return (
          <Tag>{text === 0 ? '草稿' :
            text === 1 ? '待审批' :
              text === 2 ? '审批驳回' :
                text === 3 ? '工程评审中' :
                  text === 4 ? '工程评审驳回' :
                    text === 5 ? '生产评审中' :
                      text === 6 ? '生产审批驳回' :
                        text === 7 ? '工程作业中' :
                          text === 8 ? '生产作业中' :
                            text === 9 ? '投产中' :
                              text === 10 ? '出库中' : '已完结'
          }</Tag>
        )
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Select>
            <Option value={-1}>全部</Option>
            <Option value={0}>草稿</Option>
            <Option value={1}>待审批</Option>
            <Option value={2}>审批驳回</Option>
            <Option value={3}>工程评审中</Option>
            <Option value={4}>工程评审驳回</Option>
            <Option value={5}>生产评审中</Option>
            <Option value={6}>生产审批驳回</Option>
            <Option value={7}>工程作业中</Option>
            <Option value={8}>生产作业中</Option>
            <Option value={9}>投产中</Option>
            <Option value={10}>出库中</Option>
            <Option value={11}>已完结</Option>
          </Select>
        );
      }
    },
    {
      title: '累计报废数量(PCS)',
      dataIndex: 'cstScrapNum',
      hideInSearch: true,
      width: 140
    },
    {
      title: '累计补数(PCS)',
      dataIndex: 'toBeSuppliedNum',
      hideInSearch: true,
      width: 140
    },
    {
      title: '累计返修数量(PCS)',
      dataIndex: 'chargebackNum',
      hideInSearch: true,
      width: 140
    },
    {
      title: '累计扣款金额(元)',
      dataIndex: 'deductByCust',
      hideInSearch: true,
      width: 140
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return [
          <a onClick={() => handleScrapModalVisible(record, 2)}>
            填写客户报废数量
          </a>,
          <Divider
            type="vertical"/>,
          <a
            onClick={() => handleScrapModalVisible(record, 3)}>填写客户返修数量</a>,
          <Divider type="vertical"/>,
          <a
            onClick={() => handleDeductModalVisible(record)}>填写扣款金额</a>,
          <Divider
            type="vertical"/>,
          <a
            onClick={() => handleHistoryModalVisible(record)}>履历</a>,
        ];
      }
    },
  ];

  const historyCol = [
    {
      title: '序号',
      dataIndex: 'key',
      width: 80,
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '操作时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作用户',
      dataIndex: 'createByName',
    },
    {
      title: '操作类型',
      dataIndex: 'serviceType',
      render: (text, record) => {
        return <Tag>{record.serviceType === 1? '客户扣款' : record.serviceType === 2 ? '客户报废': '客户返修'}</Tag>
      }
    },
    {
      title: '本次返修数量(PCS)',
      dataIndex: 'chargebackNum',
    },
    {
      title: '本次报废数量(PCS)',
      dataIndex: 'cstScrapNum',
    },
    {
      title: '本次补数(PCS)',
      dataIndex: 'toBeSuppliedNum',
    },
    {
      title: '本次扣款金额(元)',
      dataIndex: 'deductByCust',
    },
  ];
  const tableRef = useRef();
  return (
    <PageContainer>
      <ProTable
        style={{display: createModalVisible ? 'none' : 'block'}}
        actionRef={actionRef}
        formRef={tableRef}
        rowKey="orderId"
        sticky
        search={{
          labelWidth: 120,
        }}
        request={async (params, sorter, filter) => {
          const param = {
            ...params,
            orderStatusMin: 9, // 订单状态为9,10,11
            pageNum: params.current,
            // createBy: JSON.parse(sessionStorage.getItem('user')).sysUser.userId
          };
          const res = await queryOrder(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
      />
      <Modal
        destroyOnClose
        title={title}
        width={800}
        visible={scrapModalVisible}
        onCancel={() => setScrapModalVisible(false)}
        wrapClassName={'normalModal'}
        onOk={() => handleScrapSubmit(title === '客户报废补数' ? 2 : 3)}
      >
        <Form form={refundForm} name="transferForm">
          <Form.Item name="orderId" label="订单Id">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="orderCode" label="订单编号">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="productCode" label="产品编码">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="productionNo" label="生产编号">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name={title === '客户报废补数' ? 'cstScrapNum' : 'chargebackNum'}
                     label={title === '客户报废补数' ? '客户累计报废数量' : '客户累计返修数量'}>
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="toBeSuppliedNum" label="客户累计补数">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name={title === '客户报废补数' ? 'thisCstScrapNum' : 'thisChargebackNum'}
                     label={title === '客户报废补数' ? '本次报废数量' : '本次返修数量'} rules={[
            {
              pattern: /^[1-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={1}/>
          </Form.Item>
          <Form.Item name="thisToBeSuppliedNum" label="需要补数" rules={[
            {
              pattern: /^[1-9]\d*$/,
              message: '只能输入整数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={0}/>
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <TextArea/>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        destroyOnClose
        title={'客户扣款金额'}
        width={800}
        visible={deductModalVisible}
        onCancel={() => setDeductModalVisible(false)}
        wrapClassName={'normalModal'}
        onOk={() => handleDeductSubmit()}
      >
        <Form form={deductForm} name="transferForm">
          <Form.Item name="orderCode" label="订单编号">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="custName" label="客户">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="orderNum" label="订单数量">
            <Input disabled={true}/>
          </Form.Item>
          <Form.Item name="deductByCustNew" label="本次扣款金额(元)" rules={[
            {
              pattern: /^\d+(\.\d{0,2})?$/,
              message: '只能输入两位小数'
            }
          ]}>
            <InputNumber style={{width: '100%'}} min={1}/>
          </Form.Item>
          <Form.Item name="deductByCust" label="累计扣款金额(元)">
            <Input disabled={true}/>
          </Form.Item>
        </Form>
      </Modal>
      <Drawer
        width={1000}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        <ProDescriptions
          column={3}
          title={'售后维护履历'}
          request={async () => ({
            data: row || {},
          })}
          params={{
            id: row?.orderCode,
          }}
          columns={[
            {
              title: '订单编号',
              dataIndex: 'orderCode',
            },
            {
              title: '产品编码',
              dataIndex: 'productCode',
            },
            {
              title: '生产编号',
              dataIndex: 'productionNo',
            },
          ]}
        />
        <ProTable
          actionRef={historyRef}
          rowKey="serviceId"
          toolbar={false}
          options={false}
          request={async (params, sorter, filter) => {
            const res = await queryAfterSale({
              orderId: selectedRow.orderId,
              pageSize: 9999999,
              pageNum: 1
            })
            return {
              data: res.result.records,
              success: true,
              total: res.result.total
            }
          }}
          search={false}
          pagination={false}
          columns={historyCol}
        />
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
